<template>
    <div class="form-page">
        <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" placeholder="用户名/邮箱" />
            </el-form-item>
            <el-form-item>
                <AsyncButton class="submit-btn" :loading="loading" type="primary" @click="submitForm(formRef)">
                    确定
                </AsyncButton>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { updateMyProfile, refreshToken } from '@/api/index'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store'

const userStore = useUserStore()

const form = ref({
    username: '',
});

const rules = {
    username: [
        { required: true, message: '请输入用户名' },
    ],
}

const formRef = ref(null);

const loading = ref(false)

function submitForm(formRef) {
    formRef.validate(valid => {
        if (valid) {
            loading.value = true
            updateMyProfile(form.value).then(res => {
                console.log(res, 'res')
                loading.value = false
                if (res.code === 200) {
                    ElMessage.success(res.msg)
                    updateToken()
                } else {
                    ElMessage.error(res.msg)
                }
            }).catch(err => {
                loading.value = false
            })
        }
    });
}

function updateToken() {
    refreshToken().then(res => {
        userStore.updateToken(res.data)
    }).catch(err => {
        console.log(err)
    })
}

onMounted(() => {
    form.value.username = userStore.userInfo?.username
})
</script>

<style lang="scss">
@import '@/assets/css/form-page.scss';
</style>